package com.example.demo.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * @author gyc
 * @date 2018/1/5
 */
@Controller
public class HelloController {
    private static final Logger logger= LoggerFactory.getLogger(HelloController.class);

    //Save the uploaded file to this folder
    private static String UPLOADED_FOLDER = "E://upload//load//";


    @GetMapping("/")
    public String index() {
        return "fillupload";
    }

    @PostMapping("/upload")
    public String singleFileUpload(
            @RequestParam(value = "file")MultipartFile file,
            RedirectAttributes redirectAttributes
            ){
        if(file.isEmpty()){
            redirectAttributes.addFlashAttribute("message","Please select a file to upload");
            return "redirect:result";
        }
        try {
            byte[] bytes=file.getBytes();
            Path path = Paths.get(UPLOADED_FOLDER+file.getOriginalFilename());
            Files.write(path,bytes);
            redirectAttributes.addFlashAttribute(
                    "message",
                    "You successfully uploaded '" + file.getOriginalFilename() + "'"
                    );

        }catch (IOException e){
            e.printStackTrace();
        }
        return "redirect:result";
    }
    @GetMapping("/result")
    public String goResult(){
        return "result";
    }

}
